package cn.swust.action;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import cn.swust.model.ProductBean;
import cn.swust.service.ProductService;
import cn.swust.service.serviceimpl.ProductServiceImpl;
import cn.swust.util.DBUtil;
import cn.swust.util.Pager;
import cn.swust.util.PagerService;
import cn.swust.util.sendJson;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ProductAction extends ActionSupport{
	private ProductBean product = new ProductBean();
	private ProductService proService = new ProductServiceImpl();
	private List<ProductBean> proList= new ArrayList<ProductBean>();
	//前台分页
	private int id; //商品id
	private int type;//查询分类，
	private String sort="asc";//查询结果排序
	private int pageSize = 9; 
	private int nowPage = 1;
	private int allPage;
	private String keyWord;
	private String page;//page !=null表示点击的是分页选项
	private int count;//请求的数量
	//后台分页元素
	private Pager pager = new Pager();
	protected String currentPage;
	protected String pagerMethod;
	protected int totalRows;
	//////////////////////////////////////////后台
	public String productList()
	{
		String sql = "";
		ActionContext ac=ActionContext.getContext(); 
		Map map=ac.getSession();
		if(page!=null&&page.trim().equals("initial"))//选择了查询了条件,未出现分页查询
		{
			System.out.println("你提交的是查询条件");
			HttpServletRequest request = ServletActionContext.getRequest();
			int limit = Integer.valueOf(request.getParameter("limit"));
				if(limit>-1){
					sql += "pro_limit="+limit; map.put("limit", limit);
				}
			int classify = Integer.valueOf(request.getParameter("classify"));
				if(classify>0){
					if(sql !="")
					sql +=" and class_id="+classify; 
					else
						sql += "class_id="+classify; 
				map.put("classify", classify);
				}
			String key =request.getParameter("keyword");
				if(key!=null&&key!=""){
					if(sql!="")
					sql += " and pro_keyword like '%"+key+"%'";
					else
						sql = " pro_keyword like '%"+key+"%'";
					map.put("keyword", key.trim());
				}	
		}
		else if(page!=null&&page.trim().equals("paged"))
		{
			System.out.println("你点击的是分页");
				if(map.get("limit")!=null&&(Integer)map.get("limit")>-1){
					sql += "pro_limit="+(Integer)map.get("limit");						
					}
				if((map.get("classify")!=null&&(Integer)map.get("classify")>0)){
					if(sql!="")
					sql +=" and class_id="+(Integer)map.get("classify");
					else sql +="class_id="+(Integer)map.get("classify");
					}
				if((String)map.get("keyword")!=null){
					if(sql !="")
					sql += " and pro_keyword like '%"+(String)map.get("keyword")+"%'";
					else 		sql += "pro_keyword like '%"+(String)map.get("keyword")+"%'";
				}
		}
		if(sql!=""&&sql!=" ")
			sql ="where " +sql;
		System.out.println("查询条件拼接的sql:"+sql);
		totalRows = proService.getCountCondition(sql);//.getListNum(type);
		pager = PagerService.getPager(currentPage, pagerMethod, totalRows);
		currentPage = String.valueOf(pager.getCurrentPage());
		proList = proService.querySql(sql, pager);//.queryAllPro(pager, sort);
		return SUCCESS;
	}
	public String modPro()
	{
		System.out.println(product.getId()+":"+product.getDetailPro().getProState());
		//proService.modProduct(id, product);
		return SUCCESS;
	}
	public String delPro()
	{
		int flag =proService.delProduct(id);
		if(flag>-1)
		{
			return SUCCESS;
		}
		else
			return "error";
	}
	public String addProduct()
	{//这里需要将session中的savepath和showpath拿出来存到数据库，等更新的时候，要set到sesion中去
		ActionContext ac=ActionContext.getContext(); 
		Map map=ac.getSession();
		if((String)map.get("showpath")!=null)
		product.setPicPath((String)map.get("showpath")); //商品图片目录
		else
			product.setPicPath(DBUtil.getElement("defaultpicpath"));
		if((String)map.get("smallpic")!=null)
		product.setPicUrl((String)map.get("smallpic"));//商品略缩图路径
		else
			product.setPicUrl(DBUtil.getElement("defaultpicurl"));//商品略缩图路径
		System.out.println((String)map.get("picsname")); //所有的文件的上传图片名称:供前台放大镜效果展示
		if((String)map.get("picsname")!=null)
			product.setAllPics((String)map.get("picsname"));
		else
			product.setAllPics((String)map.get(DBUtil.getElement("defaultpicurl")));
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
		product.setStoreTime(sim.format(new Date()));
		product.setRemark(product.getRemark().trim());
		System.out.println("classID:"+product.getClassify());
		proService.addProduct(product);
		//这里清空session中的savepath和showpath
		ActionContext.getContext().getSession().remove("showpath");
		ActionContext.getContext().getSession().remove("smallpic");
		ActionContext.getContext().getSession().remove("savepath");
		ActionContext.getContext().getSession().remove("picsname");
		return SUCCESS;
	}
	public String queryOneProduct()
	{
		product = proService.queryProMoreById(id);//.queryProById(id);
		System.out.println(product.getDetailPro().getProState());
		//这里将session设置savepath和showpath值以供修改时的图片文件夹管理
		Map<String, Object> sesstion = ActionContext.getContext().getSession();
		sesstion.put("showpath",product.getPicPath());
		sesstion.put("smallpic", product.getPicUrl());
		sesstion.put("", "");
		return SUCCESS;
	}
	///////////////////////////前台///////////////////////////////
	public String getProJson()
	{
		proList = proService.queryLastProByTime(count);
		System.out.println(proList.size());
		sendJson.send(ServletActionContext.getResponse(),proList);
		return null;
	}
	//根据分类或者关键词查询商品
	public String queryProList()
	{
		if(type!=0){
		System.out.println("现在是按类别搜索");
		if(nowPage==1){ //第一次查询
			totalRows = proService.getListNum(type);
			if(totalRows==0)
				return SUCCESS;
			int temp = totalRows/pageSize;
		    if(temp==0)
		    	allPage = 1;
		    else if(temp>0&&totalRows%pageSize!=0)
		    	allPage = temp+1;
		}
		else{
			if(nowPage<1)
				nowPage =1;
			if(nowPage>allPage)
				nowPage=allPage;
		}
		System.out.println("pageSize:nowPage:type"+pageSize+" "+nowPage+" "+sort+"总记录");
		proList = proService.queryAllByCondtion(pageSize, nowPage, type, sort);
		}
		else{
			try {
				keyWord = new String(keyWord.trim().getBytes("utf-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("现在是按关键词搜索："+keyWord);
			if(nowPage==1){ //第一次查询
				totalRows = proService.getCountByKey(keyWord);
				if(totalRows==0)
					return SUCCESS;
				int temp = totalRows/pageSize;
			    if(temp==0)
			    	allPage = 1;
			    else if(temp>0&&totalRows%pageSize!=0)
			    	allPage = temp+1;
			}
			else{
				if(nowPage<1)
					nowPage =1;
				if(nowPage>allPage)
					nowPage=allPage;
			}
			System.out.println("pageSize:nowPage:keyWOrd"+pageSize+" "+nowPage+" "+sort+"总记录");
			proList = proService.queryPartProByWord(keyWord, sort, pageSize, nowPage);
		}
		return SUCCESS;
	}
	public String getDetailJson()
	{
		System.out.println("接收的id："+id);
		sendJson.send(ServletActionContext.getResponse(), proService.queryProMoreById(id));
		return null;
	}
	public ProductBean getProduct() {
		return product;
	}
	public void setProduct(ProductBean product) {
		this.product = product;
	}
	public ProductService getProService() {
		return proService;
	}
	public void setProService(ProductService proService) {
		this.proService = proService;
	}
	public List<ProductBean> getProList() {
		return proList;
	}
	public void setProList(List<ProductBean> proList) {
		this.proList = proList;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(String currentPage) {
		this.currentPage = currentPage;
	}
	public String getPagerMethod() {
		return pagerMethod;
	}
	public void setPagerMethod(String pagerMethod) {
		this.pagerMethod = pagerMethod;
	}
	
	public int getTotalRows() {
		return totalRows;
	}
	public void setTotalRows(int totalRows) {
		this.totalRows = totalRows;
	}
	public Pager getPager() {
		return pager;
	}
	public void setPager(Pager pager) {
		this.pager = pager;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getNowPage() {
		return nowPage;
	}
	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}
	public int getAllPage() {
		return allPage;
	}
	public void setAllPage(int allPage) {
		this.allPage = allPage;
	}
	public String getKeyWord() {
		return keyWord;
	}
	public void setKeyWord(String keyWord) {
		this.keyWord = keyWord;
	}
}
